/*******************************************************************************
 * Copyright 2017 Bstek
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License.  You may obtain a copy
 * of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
 * License for the specific language governing permissions and limitations under
 * the License.
 ******************************************************************************/
package com.bstek.urule.console.servlet;

import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 静态资源
 * @author:gehongbin
 * @version 1.0
 * @date 2021/12/08
 */
@Controller
public class ResourceLoaderController {

	/**
	 * 获取静态资源
	 * @param req
	 * @param resp
	 */
	@GetMapping("/urule/res/**")
	public void res(HttpServletRequest req, HttpServletResponse resp) {
		String path=req.getContextPath()+"/urule/res";
		String uri=req.getRequestURI();
		String resPath=uri.substring(path.length()+1);
		String p="classpath:"+resPath;
		if(p.endsWith(".js")){
			resp.setContentType("text/javascript");
		}else if(p.endsWith(".css")){
			resp.setContentType("text/css");
		}else if(p.endsWith(".png")){
			resp.setContentType("image/png");
		}else if(p.endsWith(".jpg")){
			resp.setContentType("image/jpeg");
		}else{
			resp.setContentType("application/octet-stream");
		}

		try{
			ClassPathResource resource = new ClassPathResource(resPath);
			InputStream input = resource.getInputStream();
			OutputStream output=resp.getOutputStream();
			IOUtils.copy(input, output);
			output.flush();
		}catch (IOException e) {
			e.printStackTrace();
		} finally{
		}
	}
}
